#!/bin/sh

BACKUP_DIR=/data/mongo/backup
BACKUP_FILE=$BACKUP_DIR/mongo_`date +"%Y%m%d"`.tar.gz
BACKUP_FILE_YESTERDAY=$BACKUP_DIR/mongo_`date +"%Y%m%d" --date "1 day ago"`.tar.gz

BACKUP_TARGET_SERVER=mysql@sys-backup06
BACKUP_TARGET_DIR=/data01/mongo

MONGOD_SCRIPT=/data/mongo/script/mongod


## ## COLD BACKUP
echo "backup start, stopping mongod."
T_START=`date +%s`

$MONGOD_SCRIPT stop
sleep 10

cd /data/mongo
tar vczf $BACKUP_FILE ./data

$MONGOD_SCRIPT start
sleep 30

T_END=`date +%s`
echo "backup done [`stat -c %s ${BACKUP_FILE}`bytes, took `expr ${T_END} - ${T_START}`secs], mongod started."


## TRANSFER TO BACKUP SERVER
for BF in $BACKUP_DIR/*
do
  if [ ! -f $BF ]; then continue; fi
  # rate limit 10Mbit/sec
  time scp -l 10000 -p $BF $BACKUP_TARGET_SERVER:$BACKUP_TARGET_DIR
  REMOTE_SIZE=`ssh $BACKUP_TARGET_SERVER "stat -c %s $BACKUP_TARGET_DIR/${BF##*/}" 2> /dev/null`
  if [ "$REMOTE_SIZE" == "`stat -c %s $BF`" ]; then
    echo "transfer ${BF##*/} success. delete from local dir."
    rm $BF
  else
    echo "transfer ${BF##*/} failed. will be transferred up on next time."
  fi
done

